<template>
  <BasicModal 
    v-bind="$attrs" @register="registerModal" 
    :title="`绑定第三方账号`" 
    wrapClassName="loginSelectModal" 
    @cancel="handleClose"
    :footer="null"
    :minHeight="260"
    :maskClosable="false"
    :canFullscreen="false"
  >
    <div class="enter-x flex min-w-64 min-h-64 justify-center">
      <div class="enter-x justify-center xl:justify-start" style="min-height: 200px">
        <Image :width="230" :preview="false" :src="compState.url" />
        <div :class="`${prefixCls}-expired`" v-if="compState.isExpired" @click="loadQrCode">
          <span>{{ compState.errMsg }}</span>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { computed, onMounted, onUnmounted, unref, ref, watch } from "vue"
  import { useDesign } from "/@/hooks/web/useDesign"
  import { Button, Divider, Image } from "ant-design-vue"
  import { useI18n } from "/@/hooks/web/useI18n"
  import * as apis from "../api"
  import { AuthStateEnum } from "../data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  const emit = defineEmits(["register", "scanSuccess", 'close'])
  const { createMessage, notification } = useMessage()
  const compState = ref<any>({
    qrCodeUrl: undefined,
    qrcodeId: undefined,
    isExpired: false,
    errMsg: "二维码已过期",
  })
  let timer: IntervalHandle
  const { t } = useI18n()
  const { prefixCls } = useDesign("qr-code-login")
  const state = ref("0")
  const idpConnectType = ref()
  const idpConnectId = ref()

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true, footer: null })
    idpConnectType.value = data.type
    idpConnectId.value = data.idpConnectId
    try {
      await loadQrCode()
    } finally {
      setModalProps({ loading: false })
    }
  })
  let timoutInstance : any = null
  //加载二维码信息
  async function loadQrCode() {
    state.value = "0"
    const resp = await apis.getIdpConnectQrcode({ 
      scene: idpConnectType.value, 
      idpConnectId: idpConnectId.value,
      consoleBindFlag: true
    })
    compState.value = { ...resp, isExpired: false, errMsg: "二维码已过期" }
    if (resp.qrcodeId) {
      openTimer(resp.qrcodeId)
    }
  }

  //监控扫码状态
  async function watchQrcodeToken(qrcodeId) {
    apis.checkIdpConnectQrcode({ qrcodeId: qrcodeId }).then(async (res) => {
       if (!res.success) {
        createMessage.error(res.msg || '绑定失败')
        closeModal()
        emit('close')
        return
      }

      let data = res.data
      if (data.status == AuthStateEnum.SCAN_TIMEOUT) {
        compState.value.isExpired = true
        clearInterval(timer)
      } else if (data.status != AuthStateEnum.SCAN_DOING) {
          state.value = "2"
          clearInterval(timer)

          // 打开用户绑定模型
          emit('scanSuccess', { ...data, idpConnectId: idpConnectId.value })
          closeModal()
      }
    }).catch((e) => {
      compState.value.isExpired = true
      compState.value.errMsg = e.message
      clearInterval(timer)
    })
  }

  /** 开启定时器 */
  function openTimer(qrcodeId) {
    watchQrcodeToken(qrcodeId)
    closeTimer()
    timer = setInterval(() => {
      watchQrcodeToken(qrcodeId)
    }, 1500)
  }

  /** 关闭定时器 */
  function closeTimer() {
    if (timer) clearInterval(timer)
    if(timoutInstance) clearTimeout(timoutInstance)
  }

  const handleClose = () => {
    closeTimer()
  }

  onUnmounted(() => {
    closeTimer()
  })
</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-qr-code-login";

  .@{prefix-cls} {
    &-expired {
      cursor: pointer;
      // background-color: rgba(0,0,0,.75);
      background: rgba(255, 255, 255, 0.95);
      z-index: 1000;
      content: "";
      width: 300px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 50%;

      transform: translate(-50%, -50%);

      span {
        position: absolute;
        left: 50%;
        top: 50%;
        color: #000000;
        white-space: nowrap;
        transform: translate(-50%, -50%);
      }
    }
  }
</style>
